<template>
    <div>
        <el-upload
            class="upload-demo"
            action="https://openbjvp.oss-cn-beijing.aliyuncs.com"
            :data="aLiYunData"
            :before-upload="beforeAvatarUpload"
            :on-preview="handlePreview"
            :on-change="handleChange"
            :on-success="changeFile"
            :on-remove="handleRemove"
            :file-list="fileList"
            :list-type="listType"
        >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
                <template v-if="this.typeText.length">只能上传&nbsp;&nbsp;{{ this.typeText }}文件</template>
                <template v-if="size">&nbsp;&nbsp;大小不超过{{ size }}M</template>
            </div>
        </el-upload>
    </div>
</template>
<script>
import axios from "axios"
export default {
    props: {
        files: {
            default: function() {
                return [] // [{name:'',url:''}] 回显
            },
        },
        fileType: {
            default: function() {
                return [] // ['.xlsx','.jpg']
            },
        },
        size: {
            default: 0, //大小 M
        },
        max: {
            default: 1, //个数
        },
        listType: {
            default: "text", // text/picture/picture-card
        },
    },
    data() {
        return {
            fileList: [],
            aLiYunData: {},
            typeText: "",
        }
    },
    watch: {
        files: {
            immediate: true,
            handler(newValue, oldValue) {
                this.fileList = newValue
            },
        },
        deep: true,
    },
    mounted() {
        // this.initAliYun()
        this.typeText = this.fileType.map(item => item + " ").join(",")
    },
    methods: {
        async initAliYun() {
            let result = await axios.post("/aliyun/token")
            this.aLiYunData["OSSAccessKeyId"] = result.data["AccessKeyId"]
            this.aLiYunData["policy"] = result.data["Base64Policy"]
            this.aLiYunData["Signature"] = result.data["Signature"]
            this.aLiYunData["root"] = result.data["Root"]
            this.aLiYunData["x-oss-security-token"] = result.data["SecurityToken"]
        },
        beforeAvatarUpload(file) {
            let type = this.getType(file)
            const isType = !this.fileType.length || this.fileType.includes(type)
            const isSize = !this.size || file.size / 1024 / 1024 < this.size
            if (!isType) {
                this.$message.error(`上传文件只能是 ${this.typeText} 格式!`)
                return false
            }
            if (!isSize) {
                this.$message.error(`传文件大小不能超过 ${this.size}MB!`)
                return false
            }
            let fileName = this.aLiYunData["root"] + file.name
            this.aLiYunData["key"] = fileName
            file.partUrl = fileName
            return isType && isSize
        },
        handleChange(file, fileList) {
            if (this.max == 1) {
                if (fileList.length > 1) {
                    fileList.shift()
                }
            }
        },
        changeFile(response, file, fileList) {
            this.$emit("setURl", fileList)
        },
        handleRemove(file, fileList) {
            this.$emit("setFile", fileList)
        },
        resetList() {
            this.fileList = []
        },
        getType(file) {
            let filename = file.name || file.url
            let lastIndex = filename.lastIndexOf(".")
            let filenameLength = filename.length
            let type = filename.substring(lastIndex + 1, filenameLength)
            return type
        },
        handlePreview(file) {
            let a = document.createElement("a")
            let event = new MouseEvent("click")
            a.download = file.name
            a.target = "_blank"
            a.href = file.url
            a.dispatchEvent(event)
        },
    },
}
</script>
<style lang="scss">
.el-upload__tip {
    width: 280px;
    display: inline-block;
    margin-left: 20px;
    line-height: 20px;
}
.el-upload-list--picture .el-upload-list__item {
    width: 250px;
    height: 120px;
    line-height: 60px;
    img {
        width: 100px;
        height: 100px;
    }
}
.el-list-leave-to {
    transition: all 0.1s;
}
.el-upload {
    float: left;
    transform: translateY(5px);
}
.el-upload-list--picture .el-upload-list__item-status-label {
    right: -22px;
    top: -15px;
    height: 36px;
}
</style>
